package com.quwan.security.auth;

import com.quwan.common.BaseController;
import com.quwan.common.constant.RedisKeyConsts;
import com.quwan.common.exception.ExpCode;
import com.quwan.common.exception.ResponseException;
import com.quwan.common.result.ApiResult;
import com.quwan.constans.AppConst;
import com.quwan.security.JwtTokenUtil;
import com.quwan.security.user.JwtUserDetails;
import com.quwan.utils.redis.Redis;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author quan
 * @date 2021-08-03 17:32
 */
@Api(tags = "后台登录")
@RestController
@RequestMapping("auth")
@RequiredArgsConstructor
public class AdminLoginController extends BaseController {
    private final AuthenticationManager authenticationManager;
    private final JwtTokenUtil jwtTokenUtil;
    private final Redis redis;
    @Value("${jwt.expiration}")
    private String loginExpireTime;

    @ApiOperation("后台登录 响应 code=8000 会返回新token")
    @PostMapping("mgr/login")
    public ApiResult adminLogin(@ApiParam("账号") @RequestParam String username,
                                @ApiParam("密码") @RequestParam String password) {
        String authUserName = String.format("%s@@" + AppConst.ADMIN_MODULE, username);
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(authUserName, password);
        Authentication authentication = null;
        try {
            authentication = authenticationManager.authenticate(upToken);
        } catch (BadCredentialsException e) {
            return ApiResult.error(ExpCode.LOGIN_ERR);
        } catch (AuthenticationException e) {
            return ApiResult.error(ExpCode.LOGIN_AUTH_ERR);
        }
        SecurityContextHolder.getContext().setAuthentication(authentication);
        final UserDetails userDetails = (JwtUserDetails) authentication.getPrincipal();
        String loginName = userDetails.getUsername();
        final String token = jwtTokenUtil.generateToken(userDetails);

        String redisUserKey = RedisKeyConsts.PLATFORM + loginName;
        redis.setToken(redisUserKey, token, Long.valueOf(loginExpireTime) * 24 * 3600);
        Map<String, Object> res = new HashMap<>();
        res.put("loginName", loginName);
        JwtUserDetails jwtUserDetails = (JwtUserDetails) userDetails;
        res.put("userId", jwtUserDetails.getId());
        res.put("token", token);
        logger.info("登录token：" + res.get("token"));
        return ApiResult.success(res);
    }
}
